package com.goudan.rabbitmq.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.CustomExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 延迟队列配置类
 */
@Configuration
public class DelayedQueueConfig {

    // 交换机  队列  routingKey
//    public static final String DELAYED_QUEUE_NAME = "delayed.queue";
//    public static final String DELAYED_EXCHANGE_NAME = "delayed.exchange";
//    public static final String DELAYED_ROUTING_KEY = "delayed.routingKey";

    @Resource
    private DelayedQueueProperties delayedQueueProperties;

    // 定义延迟队列
    @Bean
    public Queue delayedQueue() {
        return new Queue(delayedQueueProperties.getDelayedQueueName());
    }

    // 自定义交换机 我们在这里定义的是一个延迟交换机
    @Bean
    public CustomExchange delayedExchange() {
        Map<String, Object> args = new HashMap<>();
        // 自定义交换机的类型
        args.put("x-delayed-type", "direct");
        return new CustomExchange(delayedQueueProperties.getDelayedExchangeName(), "x-delayed-message", true, false, args);
    }

    @Bean
    public Binding bindingDelayedQueue(@Qualifier("delayedQueue") Queue queue,
                                       @Qualifier("delayedExchange") CustomExchange delayedExchange) {
        return BindingBuilder.bind(queue).to(delayedExchange).with(delayedQueueProperties.delayedRoutingKey).noargs();
    }
}
